<!--
  功能：功能描述
  作者：kangjie
  邮箱：kangjie@briup.com
  时间：2021年07月19日 09:58:06
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div class>
    <!-- 添加按钮 -->
    <div>
      <el-button type="primary" @click="toAdd">添加</el-button>
    </div>
    <!-- 表格 -->
    <div>
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
        <el-table-column type="index" :index="1" label="序号" width="60"></el-table-column>
        <el-table-column prop="id" label="栏目编号"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column label="图标" prop="icon">
          <template slot-scope="scope">
            <el-popover placement="right" trigger="hover">
              <el-image :src="scope.row.icon" style="width:200px;height:200px;" fit="contain"></el-image>
              <el-image
                :src="scope.row.icon"
                slot="reference"
                style="width:30px;height:30px;"
                fit="contain"
              ></el-image>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="排序号"></el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button @click="toEdit(scope.row)" type="text" size="small">编辑</el-button>
            <el-button type="text" size="small" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 6, 10, 15]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form :model="form" :rules="rules" ref="cloumnFrom">
        <el-form-item label="活动名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="序号" :label-width="formLabelWidth">
          <el-input v-model="form.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" :label-width="formLabelWidth" prop="icon">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.icon" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery, deleteById, saveOrUpdate } from "@/api/column.js";
import { showFileURL, uploadFileURL } from "@/utils/config";
export default {
  // 组件名称
  name: "demo",
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      form: {},
      loading: false,
      imageUrl: "",
      title: "",
      showFileURL,
      uploadFileURL,
      visible: false,
      tableData: [],
      formLabelWidth: "80px",
      params: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        icon: [{ required: true, message: "请选择图片", trigger: "change" }]
      }
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {
    params: {
      handler() {
        this.queryPage();
      },
      deep: true
    }
  },

  // 组件方法
  methods: {
    // 去删除
    
    async deleteById(id){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await deleteById({id});
          console.log(res);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 重载数据
          this.queryPage()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
    },
    // 去编辑
    toEdit(row) {
      this.form = { ...row };
      this.title = "编辑栏目信息";
      this.visible = true;
      this.imageUrl = this.form.icon;
    },
    // 去添加
    toAdd() {
      this.visible = true;
      this.title = "添加栏目信息";
      this.form = {};
      this.imageUrl = "";
    },
    // 分页查询栏目分类数据
    async queryPage() {
      let temp = {
        ...this.params
      };
      this.loading = true;
      let res = await pageQuery(temp);
      // console.log(res);
      this.tableData = res.data.list;
      this.total = res.data.total;
      this.loading = false;
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.pageSize = val;
      this.params.page = 1;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.page = val;
    },
    // 图片上传成功回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res);
      this.form.icon = showFileURL + res.data.id;
    },
    // 图片上传之前回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 重置表单校验
    toClose() {
      this.$refs["cloumnFrom"].resetFields();
      for(let key in this.form){
        this.form[key]='';
      }
      this.imageUrl='';
      this.visible=false;
    },
    // 去保存
    toSave() {
      this.$refs["cloumnFrom"].validate(async valid => {
        if (valid) {
          // alert('submit!');
          let res = await saveOrUpdate(this.form);
          this.$notify.success({
            title: "保存成功",
            message: res.message,
            type: "success"
          });
          this.toClose();
          this.imageUrl = "";
          this.queryPage();
          // this.visible=false;
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
  },
  // 以下是生命周期钩子
  /**
   * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
   */
  created() {
    this.queryPage();
  },
  /**
   * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
   */
  mounted() {},
  /**
   * 实例销毁之前调用。在这一步，实例仍然完全可用。
   */
  beforeDestroy() {},
  /**
   * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
   * 所有的事件监听器会被移除，所有的子实例也会被销毁。
   */
  destroyed() {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style lang='scss' >
.app-container {
  padding: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
